package com.xysoft.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.xysoft.admin.common.ElementConst;
import com.xysoft.admin.common.SessionInfo;
import com.xysoft.admin.dto.OrganizationDTO;
import com.xysoft.admin.dto.SystemTypeDTO;
import com.xysoft.admin.service.IOrganizationService;
import com.xysoft.model.Organization;
import com.xysoft.model.SystemType;
import com.xysoft.model.User;
import com.xysoft.util.JsonUtil;
import com.xysoft.util.RequestUtil;

@Component
@SuppressWarnings("unchecked")
public class OrganizationServiceImpl extends BaseServiceImpl implements IOrganizationService {
	
	@Transactional(readOnly = true)
	public String get(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		User user = (User)this.getBaseDao().get(User.class, sessionInfo.getUser().getId());
		Organization organ = user.getOrganization();
		String node = request.getParameter("node");
		//查询SQL语句
		String hql = "from Organization o where o.deleted = 0";
		//查询SQL值
		List<Object> values = new ArrayList<Object>();
		boolean isExpand = false;
		if (node == null || "root".equals(node)) {
			hql = hql + " and o.id = ?";
			values.add(organ.getId());
			isExpand = true;
		} else {
			hql = hql + " and o.keyChar like ? and o.parent.id = ?";
			values.add(organ.getKeyChar() + "%");
			values.add(Integer.valueOf(node));
		}
		List<Organization> organizations = this.getBaseDao().find(hql, values);
		List<OrganizationDTO> dtos = new ArrayList<OrganizationDTO>();
		for (Organization oo : organizations) {
			OrganizationDTO dto = new OrganizationDTO();
			BeanUtils.copyProperties(oo, dto);
			SystemType type = oo.getSystemType();
			dto.setSsystemType(type.getName());
			dto.setSsystemTypeID(type.getId());
			if (oo.getNumber() > 0) {
				dto.setExpandable(true);
				dto.setExpanded(isExpand);
				dto.setLeaf(false);
			} else {
				dto.setExpandable(false);
				dto.setLeaf(true);
			}
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional
	public Map<String,Object> addOrModify(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		String idSTR = RequestUtil.getValue(request, "id");
		Organization organ = null;
		if ("".equals(idSTR)) {
			int parentID = Integer.parseInt(RequestUtil.getValue(request, "parentID"));
			Organization parent = (Organization)this.getBaseDao().get(Organization.class, parentID);
			if (!parent.getKeyChar().startsWith(sessionInfo.getKeyChar()) || parent.isDeleted()) return null;
			//更新父节点的子节点数量
			parent.setNumber(parent.getNumber() + 1);
			this.getBaseDao().save(parent);
			organ = new Organization();
			organ.setKeyChar(parent.getKeyChar() + parent.getId() + ";");
			organ.setNumber(0);
			organ.setParent(parent);
			int typeID = Integer.parseInt(RequestUtil.getValue(request, "ssystemTypeID"));
			SystemType type = (SystemType)this.getBaseDao().get(SystemType.class, typeID);
			if (type.getValue().length() <= sessionInfo.getTypeValue().length() || type.isDeleted()) return null;
			organ.setSystemType(type);
		} else {
			int id = Integer.valueOf(idSTR);
			organ = (Organization)this.getBaseDao().get(Organization.class, id);
			if (!organ.getKeyChar().startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";") || organ.isDeleted()) return null;
		}
		organ.setDeleted(false);
		organ.setEnabled(Boolean.valueOf(RequestUtil.getValue(request, "enabled")));
		organ.setName(RequestUtil.getValue(request, "name"));
		organ.setRemark(RequestUtil.getValue(request, "remark"));
		organ.setShortName(RequestUtil.getValue(request, "shortName"));
		this.getBaseDao().save(organ);
		//返回结果
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("success", true);
		modelMap.put("title", "保存成功！");
		modelMap.put("msg", "");
		modelMap.put("obj", organ.getId());
		return modelMap;
	}

	@Transactional
	public Map<String, Object> del(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int id = Integer.parseInt(RequestUtil.getValue(request, "id"));
		Organization organ = (Organization)this.getBaseDao().get(Organization.class, id);
		if (!organ.getKeyChar().startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";") || organ.isDeleted()) return null;
		List<Organization> organs = this.getBaseDao().find("from Organization o where o.deleted = 0 and o.keyChar like ?", 
				organ.getKeyChar() + organ.getId() + ";%");
		List<User> users = this.getBaseDao().find("from User u where u.deleted = 0 and u.organization.id = ?", id);
		Map<String,Object> modelMap = new HashMap<String,Object>(4);
		modelMap.put("success", true);
		if (organs.size() < 1) {
			if (users.size() < 1) {
				organ.setDeleted(true);
				this.getBaseDao().save(organ);
				Organization parent = organ.getParent();
				parent.setNumber(parent.getNumber() - 1);
				this.getBaseDao().save(parent);
				this.getBaseDao().exec("update Role r set r.deleted = 0 where r.organization.id = ?", id);
				modelMap.put("ok", true);
				modelMap.put("title", "删除成功！");
				modelMap.put("msg", "");
			} else {
				modelMap.put("ok", false);
				modelMap.put("title", "删除失败！");
				modelMap.put("msg", "请确定该组织下的所有用户已删除或已转移！");
			}
		} else {
			modelMap.put("ok", false);
			modelMap.put("title", "删除失败！");
			modelMap.put("msg", "请确定该组织下的子组织已删除！");
		}
		return modelMap;
	}

	@Transactional(readOnly = true)
	public String getLevel(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		String hql = "from SystemType s where s.deleted = 0 and s.belong = ? and s.value like ? and LENGTH(s.value) > ?";
		List<Object> values = new ArrayList<Object>();
		values.add(ElementConst.LEVELTYPE);
		int id = Integer.valueOf(RequestUtil.getValue(request, "id"));
		int dex = Integer.valueOf(RequestUtil.getValue(request, "dex"));
		SystemType sts = (SystemType)this.getBaseDao().get(SystemType.class, id);
		if (sts.getValue().length() < sessionInfo.getTypeValue().length() || sts.isDeleted()) return null;
		values.add(sts.getValue() + "%");
		values.add((long)sts.getValue().length() - dex);
		List<SystemType> types = this.getBaseDao().find(hql, values);
		List<SystemTypeDTO> dtos = new ArrayList<SystemTypeDTO>();
		for (SystemType type : types) {
			SystemTypeDTO dto = new SystemTypeDTO();
			dto.setId(type.getId());
			dto.setName(type.getName());
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

}
